<template>
	<view class="login-container">
		<!-- Logo -->
		<view class="logo-container">
			<image src="/static/u408.png" class="logo" mode="aspectFit"></image>
		</view>

		<!-- 标题 -->
		<view class="title-container">
			<text class="title">{{ loginType === 'wechat' ? '微信授权登录' : '账号密码登录' }}</text>
			<text class="subtitle" v-if="!isUserSwitch">欢迎使用家医</text>
			<text class="subtitle switch-tip" v-else>请输入密码完成家庭成员切换</text>
		</view>

		<!-- 表单 -->
		<view class="form-container">
			<!-- 微信授权登录 -->
			<view v-if="loginType === 'wechat'">
				<!-- 授权说明 -->
				<view class="auth-description">
					<text class="auth-text">为了更好地为您提供服务，需要获取您的手机号码</text>
				</view>

				<!-- 用户协议 -->
				<view class="agreement-container">
					<checkbox-group @change="onAgreementChange">
						<label class="agreement-label">
							<checkbox value="agree" :checked="isAgreed" color="#4A90E2" />
							<text class="agreement-text">
								我已阅读并同意
								<text class="agreement-link" @click="showUserAgreement">《用户隐私政策》</text>
							</text>
						</label>
					</checkbox-group>
				</view>

				<!-- 微信授权登录按钮 -->
				<button class="wechat-login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
					:disabled="!isAgreed">
					<text class="btn-text">微信授权登录</text>
				</button>

				<!-- 其他登录方式 -->
				<view class="other-login">
					<text class="other-text">其他登录方式</text>
					<view class="other-methods">
						<text class="link-text" @click="switchToPassword">账号密码登录</text>
						<text class="link-text" @click="register">注册新用户</text>
					</view>
				</view>
			</view>

			<!-- 账号密码登录 -->
			<view v-else>
				<!-- 手机号输入 -->
				<view class="input-group">
					<text class="input-label">手机号</text>
					<view class="input-container">
						<input class="input-field" type="number" placeholder="请输入手机号" v-model="phone" maxlength="11" />
					</view>
				</view>

				<!-- 密码输入 -->
				<view class="input-group">
					<text class="input-label">密码</text>
					<view class="input-container">
						<input class="input-field" type="password" placeholder="请输入密码" v-model="password" />
					</view>
				</view>

				<!-- 用户协议 -->
				<view class="agreement-container">
					<checkbox-group @change="onAgreementChange">
						<label class="agreement-label">
							<checkbox value="agree" :checked="isAgreed" color="#4A90E2" />
							<text class="agreement-text">
								我已阅读并同意
								<text class="agreement-link" @click="showUserAgreement">《用户隐私政策》</text>
							</text>
						</label>
					</checkbox-group>
				</view>

				<!-- 登录按钮 -->
				<button class="login-btn" @click="passwordLogin" :disabled="!canPasswordLogin">
					登录
				</button>

				<!-- 忘记密码和其他方式 -->
				<view class="other-login">
					<view class="other-methods">
						<text class="link-text" @click="switchToWechat">微信授权登录</text>
						<text class="link-text" @click="register">注册新用户</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { loginByPhoneApi, loginByPasswordApi } from '@/api/login.js'
import { useUserStore } from '@/store/user.js'

// 用户状态管理
const userStore = useUserStore()

// 响应式数据
const isAgreed = ref(false)
const loginType = ref('wechat') // 'wechat' 微信授权登录, 'password' 账号密码登录
const phone = ref('')
const password = ref('')
const isUserSwitch = ref(false) // 是否是用户切换模式

// 页面加载时接收参数
onLoad((options) => {
	// 如果有预填充的手机号，自动切换到密码登录模式并填充手机号
	if (options.phone) {
		loginType.value = 'password'
		phone.value = options.phone
		isUserSwitch.value = true // 标记为用户切换模式
		isAgreed.value = true // 用户切换时自动同意协议
		console.log('预填充手机号:', options.phone)
	}

	// 如果指定了登录类型，切换到对应模式
	if (options.type === 'password') {
		loginType.value = 'password'
	}
})

// 计算属性
const canPasswordLogin = computed(() => {
	return phone.value.length === 11 && password.value.length > 0 && isAgreed.value
})

// 方法定义
const onAgreementChange = (e) => {
	isAgreed.value = e.detail.value.includes('agree')
}

const showUserAgreement = () => {
	// 显示用户协议页面
	uni.showModal({
		title: '用户隐私政策',
		content: '这里是用户隐私政策的内容...',
		confirmText: '我知道了'
	})
}

const getPhoneNumber = (event) => {
	console.log('获取手机号回调:', event)

	if (event.detail.errMsg === 'getPhoneNumber:ok') {
		uni.login({
			success(res) {
				// 调用接口，发送请求到后端
				loginByPhoneApi({
					iv: event.detail.iv,
					encryptedData: event.detail.encryptedData,
					code: res.code,
					appId: 'wxad91c18755b4ac3b',
					appSecret: '9b40ca238ae92ca82f3e44d2b602134b'
				}).then(async res => {
					if (res.code == 200) {
						// 保存token到本地存储
						uni.setStorageSync('user_token', res.token)

						// 保存用户信息到状态管理
						if (res.data) {
							userStore.userInfo = res.data
						}

						// 获取完整的用户信息并存储到状态机
						await userStore.getUserInfoAction()

						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})

						// 登录成功后跳转到首页
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/home'
							})
						}, 1500)
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				}).catch(() => {
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					})
				})
			},
		})
	} else {
		// 用户拒绝授权
		uni.showToast({
			title: '需要授权手机号才能登录',
			icon: 'none'
		})
	}
}

// 切换到密码登录
const switchToPassword = () => {
	loginType.value = 'password'
}

// 切换到微信登录
const switchToWechat = () => {
	loginType.value = 'wechat'
}

// 密码登录
const passwordLogin = () => {
	if (!canPasswordLogin.value) {
		return
	}

	uni.showLoading({
		title: '登录中...'
	})

	loginByPasswordApi({
		phone: phone.value,
		password: password.value
	}).then(async res => {
		uni.hideLoading()
		if (res.code == 200) {
			// 保存token到本地存储
			uni.setStorageSync('user_token', res.token)

			// 保存用户信息到状态管理
			if (res.data) {
				userStore.userInfo = res.data
			}

			// 获取完整的用户信息并存储到状态机
			await userStore.getUserInfoAction()

			uni.showToast({
				title: isUserSwitch.value ? '切换用户成功' : '登录成功',
				icon: 'success'
			})

			// 登录成功后跳转到首页
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/home/home'
				})
			}, 1500)
		} else {
			uni.showToast({
				title: res.message || '登录失败',
				icon: 'none'
			})
		}
	}).catch(() => {
		uni.hideLoading()
		uni.showToast({
			title: '登录失败，请重试',
			icon: 'none'
		})
	})
}

const register = () => {
	// 跳转到注册页面
	uni.navigateTo({
		url: '/pages/register/register'
	})
}
</script>

<style scoped>
.login-container {
	min-height: 100vh;
	padding: 0 40rpx;
	position: relative;
}

.back-btn {
	position: absolute;
	top: 60rpx;
	left: 40rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 10;
}

.back-icon {
	font-size: 36rpx;
	color: #333;
	font-weight: bold;
}

.logo-container {
	display: flex;
	justify-content: center;
	margin-top: 120rpx;
	margin-bottom: 60rpx;
}

.logo {
	width: 120rpx;
	height: 120rpx;
}

.title-container {
	text-align: center;
	margin-bottom: 80rpx;
}

.title {
	display: block;
	font-size: 48rpx;
	font-weight: 500;
	color: #333;
	margin-bottom: 20rpx;
}

.subtitle {
	display: block;
	font-size: 28rpx;
	color: #999;
}

.form-container {
	width: 100%;
}

.auth-description {
	text-align: center;
	margin-bottom: 60rpx;
}

.auth-text {
	font-size: 28rpx;
	color: #666;
	line-height: 1.5;
}

.input-group {
	margin-bottom: 40rpx;
}

.input-label {
	display: block;
	font-size: 32rpx;
	color: #333;
	margin-bottom: 20rpx;
}

.input-container {
	background: #fff;
	border-radius: 12rpx;
	padding: 0 24rpx;
	height: 88rpx;
	border: 2rpx solid #e5e5e5;
	display: flex;
	align-items: center;
}

.input-field {
	flex: 1;
	font-size: 32rpx;
	color: #333;
}

.agreement-container {
	margin: 40rpx 0;
}

.agreement-label {
	display: flex;
	align-items: flex-start;
}

.agreement-text {
	font-size: 26rpx;
	color: #666;
	margin-left: 16rpx;
	line-height: 1.5;
}

.agreement-link {
	color: #4A90E2;
}

.wechat-login-btn {
	width: 100%;
	height: 88rpx;
	background: #07C160;
	color: white;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
	margin: 60rpx 0 40rpx 0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.wechat-login-btn:disabled {
	background: #ccc;
}

.wechat-icon {
	width: 40rpx;
	height: 40rpx;
	margin-right: 16rpx;
}

.btn-text {
	color: white;
}

.other-login {
	text-align: center;
	margin-top: 60rpx;
}

.other-text {
	font-size: 26rpx;
	color: #999;
	margin-bottom: 30rpx;
	display: block;
}

.other-methods {
	display: flex;
	justify-content: space-between;
}

.login-btn {
	width: 100%;
	height: 88rpx;
	background: #4A90E2;
	color: white;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
	margin: 60rpx 0 40rpx 0;
}

.login-btn:disabled {
	background: #ccc;
}

.forgot-password {
	font-size: 26rpx;
	color: #4A90E2;
	margin-bottom: 30rpx;
	display: block;
	text-align: center;
}

.link-text {
	font-size: 28rpx;
	color: #4A90E2;
}

/* 用户切换模式样式 */
.switch-tip {
	color: #FF8C00 !important;
	font-weight: 500;
}
</style>
